<template>
    <div class="container" height="100%">
        <div class="header">
            <span>个人资料</span>
            <el-menu class="el-menu-demo" @select="handleSelect" close-on-click-outside:true>
                <el-sub-menu index="dropdown">
                    <template #title>设置</template> 
                    <el-menu-item index="0">编辑资料</el-menu-item>
                    <el-menu-item index="1">修改密码</el-menu-item>
                    <el-menu-item index="2">退出登录</el-menu-item>
                </el-sub-menu>
            </el-menu>
        </div>

        <div class="main">
            <div class="profile-view">
                <div class="profile-item">
                    <label>姓名</label>
                    <span class="readonly">{{ profile.name }}</span>
                </div>
                <div class="profile-item">
                    <label>性别</label>
                    <span class="readonly"> {{ profile.sex == 0 ? "女" : "男" }}</span>
                </div>
                <div class="profile-item">
                    <label>工号</label>
                    <span class="readonly">{{ profile.empId }}</span>
                </div>
                <div class="profile-item">
                    <label>所属部门</label>
                    <span class="readonly">{{ profile.deptName }}</span>
                </div>
                <div class="profile-item" style="margin-bottom: 10px">
                    <label>职位</label>
                    <span class="readonly">{{ profile.posName }}</span>
                </div>
                <div class="profile-item">
                    <label>电子邮箱</label>
                    <span class="readonly">{{ profile.email }}</span>
                </div>
                <div class="profile-item">
                    <label>电话号码</label>
                    <span class="readonly">{{ profile.phone }}</span>
                </div>
                <div class="profile-item">
                    <label>地区</label>
                    <span class="readonly">{{ profile.address }}</span>
                </div>
                <div class="profile-item" style="margin-bottom: 10px">
                    <label>详细地址</label>
                    <span class="readonly">{{ profile.detailedAddress }}</span>
                </div>
                <div class="profile-item">
                    <label>出生日期</label>
                    <span class="readonly">{{ profile.birth }}</span>
                </div>
                <div class="profile-item">
                    <label>婚姻状况</label>
                    <span class="readonly">{{
                        profile.maritalStatus == 0 ? "未婚" : "已婚"
                        }}</span>
                </div>
                <div class="profile-item">
                    <label>民族</label>
                    <span class="readonly">{{ profile.ethnicity }}</span>
                </div>
                <div class="profile-item">
                    <label>籍贯</label>
                    <span class="readonly">{{ profile.nationality }}</span>
                </div>
                <div class="profile-item">
                    <label>政治面貌</label>
                    <span class="readonly">{{
                        getPoliticalLabel(profile.political)
                        }}</span>
                </div>
                <div class="profile-item" style="margin-bottom: 10px;">
                    <label>最高学历</label>
                    <span class="readonly">{{
                        getEducationLabel(profile.highestEducation)
                        }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部导航栏 -->
    <div class="footer">
        <el-tabs :tab-position="'bottom'" class="tabs" v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="工作中心" name="工作中心" class="custom-tab"></el-tab-pane>
            <el-tab-pane label="我的" name="我的" class="custom-tab"></el-tab-pane>
        </el-tabs>
    </div>

    <!-- 编辑页面 -->
    <el-drawer v-model="drawer" :direction="ttb" size="100%" :before-close="cancelClick">
        <template #header>
            <h2>编辑个人资料</h2>
        </template>
        <template #default>
            <div class="edit-content">
                <div class="edit-item">
                    <label>电子邮箱</label>
                    <input type="email" v-model="editProfile.email" />
                </div>
                <div class="edit-item">
                    <label>电话号码</label>
                    <input type="text" v-model="editProfile.phone" />
                </div>
                <div class="edit-item">
                    <label>地区</label>
                    <el-cascader v-model="editAddress" :options="regionData" @change="formatAddress"
                        popper-class="custom-popper" style="width: 100%">
                    </el-cascader>
                </div>
                <div class="edit-item">
                    <label>详细地址</label>
                    <input type="text" v-model="editProfile.detailedAddress" />
                </div>
                <div class="edit-item">
                    <label>婚姻状况</label>
                    <select v-model="editProfile.maritalStatus">
                        <option value="0">未婚</option>
                        <option value="1">已婚</option>
                    </select>
                </div>
                <div class="edit-item">
                    <label>政治面貌</label>
                    <select v-model="editProfile.political">
                        <option value="0">群众</option>
                        <option value="1">共青团员</option>
                        <option value="2">中共党员</option>
                    </select>
                </div>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelClick">取消</el-button>
                <el-button type="primary" @click="confirmClick">保存</el-button>
            </div>
        </template>
    </el-drawer>

    <!-- 修改密码 -->
    <!-- 在template部分修改drawer内容 -->
    <el-drawer v-model="drawer2" :direction="ttb" size="100%" :before-close="cancelPasswordClick">
        <template #header>
            <h2>修改密码</h2>
        </template>
        <template #default>
            <div class="edit-content">
                <div class="edit-item">
                    <label>旧密码</label>
                    <input type="password" v-model="editPassword.oldPassword" placeholder="请输入你的旧密码" />
                </div>
                <div class="edit-item">
                    <label>新密码</label>
                    <input type="password" v-model="editPassword.newPassword" placeholder="密码需6-15位，包含大小写字母和数字" />
                </div>
                <div class="edit-item">
                    <label>确认新密码</label>
                    <input type="password" v-model="editPassword.confirmNewPassword" placeholder="需与新密码保持一致" />
                </div>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelPasswordClick">取消</el-button>
                <el-button type="primary" @click="confirmPasswordClick">保存</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script>
import { ElMessage } from "element-plus";
import { queryEmpInfo, updateEmployee} from "../../api/basedata";
import { updatePassword } from "../../api/basedata";
import { regionData } from "element-china-area-data";
import { ElMessageBox } from "element-plus";
import { ref } from "vue";
import { getSessionStorageObj } from "../../utils/common.js";
import { createUserStore } from "../../state/user.js";
import { th } from "element-plus/es/locales.mjs";
const activeName = ref("我的");

export default {
    data() {
        return {
            regionData,
            drawer: false,
            drawer2: false,
            ttb: "rtl",
            isEditing: false,
            isLoading: false,
            activeName: "我的",
            profile: {
                name: "",
                sex: "",
                empId: "",
                deptName: "",
                posName: "",
                email: "",
                phone: "",
                detailedAddress: "",
                address: "",
                birth: "",
                maritalStatus: "",
                ethnicity: "",
                nationality: "",
                political: "",
                highestEducation: "",
                password: ""
            },
            politicalOptions: [
                { value: "0", label: "群众" },
                { value: "1", label: "共青团员" },
                { value: "2", label: "中共党员" },
                { value: "3", label: "其他" },
            ],
            educationOptions: [
                { value: "0", label: "小学" },
                { value: "1", label: "初中" },
                { value: "2", label: "高中" },
                { value: "3", label: "大专" },
                { value: "4", label: "本科" },
                { value: "5", label: "硕士" },
                { value: "6", label: "博士" },
                { value: "7", label: "其他" },
            ],
            editProfile: {
                empId: "",
                phone: "",
                email: "",
                address: "",
                detailedAddress: "",
                maritalStatus: "",
            },
            editPassword: {
                oldPassword: "",
                newPassword: "",
                confirmNewPassword: ""
            },
            comfirmPassword: {
                empId: "",
                password: "",
            },
            editAddress: [],
            activeIndex: "",
        };
    },
    mounted() {
        //得到全局数据
        let userInfo = getSessionStorageObj('userInfo');
        this.profile.empId = userInfo.empId
        console.log("userInfo", userInfo);
        console.log("profile", this.profile);
        this.getEmpData();
    },
    methods: {
        handleSelect(key, keyPath) {
            console.log(key, keyPath);
            this.activeIndex
            if (key === '0') {
                this.drawer = true;
            }
            else if (key === '1') {
                this.drawer2 = true;
            } else if (key === '2') {
                this.$router.push('/login');
            }
        },
        handleTabClick(tab) {
            console.log(tab)
            console.log(tab.props.name)
            if (tab.props.name === "工作中心") {
                this.$router.push('/betch');
            } else if (tab.props.name === "我的") {
                this.$router.push('/myCenter');
                console.log("我的")
            }
        },
        getEmpData() {
            this.isLoading = true;
            const empId = this.profile.empId;
            queryEmpInfo({ empId }).then((res) => {
                this.profile = res.result;
                this.editProfile = {
                    empId: this.profile.empId,
                    phone: this.profile.phone,
                    email: this.profile.email,
                    address: this.profile.address,
                    detailedAddress: this.profile.detailedAddress,
                    maritalStatus: this.profile.maritalStatus,
                    political: this.profile.political,
                };
                this.editAddress = this.parseAreaCode(this.editProfile.address);
                console.log(this.profile);
            });
        },
        getPoliticalLabel(value) {
            const option = this.politicalOptions.find((item) => item.value === value);
            return option ? option.label : "未知";
        },
        getEducationLabel(value) {
            const option = this.educationOptions.find((item) => item.value === value);
            return option ? option.label : "未知";
        },
        // 格式化地址
        formatAddress() {
            if (this.editAddress && this.editAddress.length === 3) {
                const [provinceCode, cityCode, districtCode] = this.editAddress;
                const province = this.findAreaName(provinceCode);
                const city = this.findAreaName(cityCode);
                const district = this.findAreaName(districtCode);
                this.editProfile.address = `${province}/${city}/${district}`;
            }
        },

        // 查找地区名称
        findAreaName(code) {
            const area = this.findAreaByCode(code);
            return area ? area.label : "";
        },

        // 递归查找地区
        findAreaByCode(code, options = this.regionData) {
            for (const option of options) {
                if (option.value === code) {
                    return option;
                }
                if (option.children) {
                    const result = this.findAreaByCode(code, option.children);
                    if (result) {
                        return result;
                    }
                }
            }
            return null;
        },

        // 解析地区代码
        parseAreaCode(address) {
            if (!address) return [];

            // 按 / 分割省、市、区
            const [provinceName, cityName, districtName] = address.split("/");

            // 查找省代码
            const provinceCode = this.findCodeByName(provinceName, this.regionData);
            if (!provinceCode) return []; // 如果找不到省，直接返回空数组

            // 查找市代码
            const provinceData = this.findAreaByCode(provinceCode, this.regionData);
            const cityCode = this.findCodeByName(
                cityName,
                provinceData.children || []
            );
            if (!cityCode) return [provinceCode]; // 如果找不到市，返回省代码

            // 查找区代码
            const cityData = this.findAreaByCode(
                cityCode,
                provinceData.children || []
            );
            const districtCode = this.findCodeByName(
                districtName,
                cityData.children || []
            );

            return [provinceCode, cityCode, districtCode];
        },
        // 根据名称查找代码
        findCodeByName(name, options) {
            for (const option of options) {
                if (option.label === name) {
                    return option.value;
                }
                if (option.children) {
                    const result = this.findCodeByName(name, option.children);
                    if (result) {
                        return result;
                    }
                }
            }
            return null;
        },
        cancelClick() {
            ElMessageBox.confirm("是否保存更改？", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.confirmClick();
                })
                .catch(() => {
                    ElMessage.info("取消编辑");
                    this.drawer = false;
                });
        },
        confirmClick() {
            if (!this.validateInput()) {
                return;
            }
            this.formatAddress();
            console.log(this.editProfile);
            updateEmployee(this.editProfile)
                .then(() => {
                    this.profile = { ...this.profile, ...this.editProfile };
                    ElMessage.success("修改成功");
                })
                .catch(() => {
                    ElMessage.error("修改失败");
                });
            this.drawer = false;
        },
        validateInput() {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(this.editProfile.email)) {
                ElMessage.error("请输入有效的邮箱地址");
                return false;
            }
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(this.editProfile.phone)) {
                ElMessage.error("请输入有效的电话号码");
                return false;
            }
            if (!this.editProfile.detailedAddress.trim()) {
                ElMessage.error("详细地址不能为空");
                return false;
            }
            if (!this.editProfile.maritalStatus) {
                ElMessage.error("请选择婚姻状况");
                return false;
            }
            if (!this.editProfile.political) {
                ElMessage.error("请选择政治面貌");
                return false;
            }
            if (!this.editProfile.address) {
                ElMessage.error("请选择地区");
                return false;
            }
            return true;
        },
        validatePassword(password) {
            const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,15}$/;
            return regex.test(password);
        },

        // 验证逻辑
        validateForm() {
            let isValid = true;
            this.comfirmPassword = {
                empId: this.profile.empId,
                password: this.editPassword.newPassword
            };
            // 验证旧密码
            if (!this.editPassword.oldPassword.trim()) {
                ElMessage.error("旧密码不能为空");
                isValid = false;
                return isValid;
            }
            if (this.editPassword.oldPassword != this.profile.password) {
                console.log(this.editPassword.oldPassword, this.profile.password)
                ElMessage.error("旧密码错误");
                isValid = false;
                return isValid;
            }
            // 验证新密码格式
            if (!this.validatePassword(this.editPassword.newPassword)) {
                ElMessage.error("密码需6-15位，包含大小写字母和数字");
                isValid = false;
                return isValid;
            }
            // 新增验证：新旧密码不能一致
            if (this.editPassword.oldPassword === this.editPassword.newPassword) {
                ElMessage.error("新密码不能与旧密码相同");
                isValid = false;
                return isValid;
            }
            // 验证两次新密码一致性
            if (this.editPassword.newPassword !== this.editPassword.confirmNewPassword) {
                ElMessage.error("两次输入的新密码不一致");
                isValid = false;
            }
            return isValid;
        },
        confirmPasswordClick() {
            if (!this.validateForm()) return;
            updatePassword(this.comfirmPassword)
                .then(() => {
                    ElMessage.success("密码修改成功");
                })
                .catch(() => {
                    ElMessage.error("密码修改失败");
                });
            this.cancelPasswordClick();


        },

        cancelPasswordClick() {
            this.profile.password = this.editPassword.newPassword;
            console.log("新密码："+this.profile.password)
            // 清空密码输入框
            // 重置表单
            this.editPassword = {
                oldPassword: "",
                newPassword: "",
                confirmNewPassword: ""
            };
            this.comfirmPassword = {
                empId: "",
                password: "",
            };
            this.drawer2 = false;
        }
    },
};
</script>

<style scoped>
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0px;
    background-color: #e1efff;
}

.container {
    margin: 0 auto;
    background-color: #e1efff;
}

.header {
    margin: 0;
    position: fixed;
    top: 0;
    display: flex;
    align-items: center;
    text-align: center;
    background-color:white;
    width: 100%;
    height: 8vh;
    justify-content: flex-end;
}

span {
    color: #333;
    text-align: center;
    flex-grow: 1;
    font-size: 20px;
}

/* 原代码中的 .el-menu 修改为： */
.el-menu {
    position: fixed;
    top: 0;
    right: 0;
    border: none;
    margin: 0; 
    padding: 0 10px;
    height: 8vh !important;
    width: 116px !important;
}

:deep(.el-sub-menu__title:hover) {
    background-color: white !important;
}
:deep(.el-sub-menu__title) {
    text-align: center !important;
    height: 8vh !important;
}
:deep(.el-menu-item) {
    text-align: center !important;
    padding: 0 20px !important;
}

/* 新增下拉菜单定位修正 */
.el-sub-menu__popper {
    position: fixed;
    top: 50px;
    right: 20px;
    margin-top: 5px;
}


.main {
    padding: 10px 10px 0 10px;
    margin-top: 8vh;
    /* 确保内容不会被 header 遮挡 */
    margin-bottom: 30px; 
    /* 确保内容不会被 footer 遮挡 */
}

.profile-view {
    display: flex;
    flex-direction: column;
}

.profile-item {
    display: flex;
    align-items: center;
    padding: 15px 10px;
    border-bottom: 1px solid #eee;
    background-color: white;
}

label {
    width: 100px;
    font-weight: bold;
    color: #666;
}

.readonly {
    flex: 1;
    font-size: 15px;
    color: #999;
    text-align: justify;
}

/* 编辑页面样式 */

.edit-content {
    padding: 20px;
}

.edit-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
}

.edit-item label {
    margin-bottom: 5px;
}

.edit-item input,
.edit-item select {
    padding: 8px;
    border: 1px solid #ddd;
    color: #666;
    border-radius: 4px;
}

.footer {
    position: fixed;
    bottom: 0;
    /* 将 footer 推到页面底部 */
    width: 100vh;
    height: 6vh;
    /* 确保 footer 宽度占满整个页面 */
    background-color: #f5f5f5;
    z-index: 1000;
}

:deep(.tabs .el-tabs__nav) {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    width: 100%;
    /* 确保导航栏宽度占满整个容器 */
    position: fixed;
    bottom: 0;
}

:deep(.tabs .el-tabs__nav) {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  width: 100%;
  /* 确保导航栏宽度占满整个容器 */
  position: fixed;
  bottom: 0;
}

:deep(.tabs .el-tabs__item) {
  flex: none;
  /* 不平分宽度 */
  text-align: center;
  /* 文字居中 */
  width: 30%;
  /* 每个标签占 50% */
  font-weight: bold;
  font-size: 18px;
}


:deep(.tabs .el-tabs__item) {
    flex: none;
    /* 不平分宽度 */
    text-align: center;
    /* 文字居中 */
    width: 30%;
    /* 每个标签占 50% */
    font-weight: bold;
    font-size: 18px;
}


@media (max-width: 412px) {
    :deep(.custom-popper) {
        width: 90vw !important;
        /* 限制最大宽度 */
        left: 5vw !important;
        /* 居中显示 */
    }
}
</style>

<style>
.custom-popper {
    width: 360px !important;
    /* 限制最大宽度 */
    left: 8px !important;
    /* 居中显示 */
}


.custom-popper .el-cascader-menu{
    min-width: 120px !important;
    padding:0;
    /* width:120px !important; */
}

.custom-popper .el-cascader-menu__wrap {
    width: 110px;
}


</style>